package com.example.service;

import com.example.model.MerchantService;
import com.example.repository.MerchantServiceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 商家服务Service类
 */
@Slf4j
@Service
public class MerchantServiceService {

    @Autowired
    private MerchantServiceRepository merchantServiceRepository;

    @Autowired
    private WebSocketService webSocketService;

    /**
     * 创建商家服务
     */
    @Transactional
    public MerchantService createService(MerchantService service) {
        service.setCreatedAt(LocalDateTime.now());
        service.setUpdatedAt(LocalDateTime.now());
        
        MerchantService savedService = merchantServiceRepository.save(service);
        log.info("创建商家服务: id={}, merchantId={}, title={}", 
                savedService.getId(), savedService.getMerchantId(), savedService.getTitle());
        
        return savedService;
    }

    /**
     * 更新商家服务
     */
    @Transactional
    public MerchantService updateService(Long id, MerchantService service) {
        Optional<MerchantService> existingOpt = merchantServiceRepository.findById(id);
        if (existingOpt.isEmpty()) {
            throw new RuntimeException("服务不存在: id=" + id);
        }

        MerchantService existing = existingOpt.get();
        existing.setTitle(service.getTitle());
        existing.setDescription(service.getDescription());
        existing.setCategory(service.getCategory());
        existing.setServiceType(service.getServiceType());
        existing.setPrice(service.getPrice());
        existing.setOriginalPrice(service.getOriginalPrice());
        existing.setDurationMinutes(service.getDurationMinutes());
        existing.setImageUrls(service.getImageUrls());
        existing.setTags(service.getTags());
        existing.setServiceArea(service.getServiceArea());
        existing.setContactPhone(service.getContactPhone());
        existing.setContactAddress(service.getContactAddress());
        existing.setBusinessHours(service.getBusinessHours());
        existing.setIsRecommended(service.getIsRecommended());
        existing.setIsPopular(service.getIsPopular());
        existing.setSortOrder(service.getSortOrder());
        existing.setExtraInfo(service.getExtraInfo());
        existing.setUpdatedAt(LocalDateTime.now());

        MerchantService updatedService = merchantServiceRepository.save(existing);
        log.info("更新商家服务: id={}, title={}", updatedService.getId(), updatedService.getTitle());
        
        return updatedService;
    }

    /**
     * 发布服务
     */
    @Transactional
    public void publishService(Long id) {
        Optional<MerchantService> serviceOpt = merchantServiceRepository.findById(id);
        if (serviceOpt.isEmpty()) {
            throw new RuntimeException("服务不存在: id=" + id);
        }

        MerchantService service = serviceOpt.get();
        service.setStatus(MerchantService.ServiceStatus.PUBLISHED);
        service.setPublishedAt(LocalDateTime.now());
        service.setUpdatedAt(LocalDateTime.now());

        merchantServiceRepository.save(service);
        log.info("发布服务: id={}, title={}", service.getId(), service.getTitle());

        // 通过WebSocket通知用户有新服务发布
        notifyNewServicePublished(service);
    }

    /**
     * 暂停服务
     */
    @Transactional
    public void suspendService(Long id) {
        Optional<MerchantService> serviceOpt = merchantServiceRepository.findById(id);
        if (serviceOpt.isEmpty()) {
            throw new RuntimeException("服务不存在: id=" + id);
        }

        MerchantService service = serviceOpt.get();
        service.setStatus(MerchantService.ServiceStatus.SUSPENDED);
        service.setUpdatedAt(LocalDateTime.now());

        merchantServiceRepository.save(service);
        log.info("暂停服务: id={}, title={}", service.getId(), service.getTitle());
    }

    /**
     * 删除服务
     */
    @Transactional
    public void deleteService(Long id) {
        merchantServiceRepository.deleteById(id);
        log.info("删除服务: id={}", id);
    }

    /**
     * 获取服务详情
     */
    public Optional<MerchantService> getServiceById(Long id) {
        return merchantServiceRepository.findById(id);
    }

    /**
     * 获取服务详情并增加浏览次数
     */
    @Transactional
    public Optional<MerchantService> getServiceByIdAndIncrementViewCount(Long id) {
        Optional<MerchantService> serviceOpt = merchantServiceRepository.findById(id);
        if (serviceOpt.isPresent()) {
            merchantServiceRepository.incrementViewCount(id);
        }
        return serviceOpt;
    }

    /**
     * 根据商家ID获取服务列表
     */
    public List<MerchantService> getServicesByMerchant(String merchantId) {
        return merchantServiceRepository.findByMerchantIdOrderByCreatedAtDesc(merchantId);
    }

    /**
     * 分页根据商家ID获取服务列表
     */
    public Page<MerchantService> getServicesByMerchant(String merchantId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findByMerchantIdOrderByCreatedAtDesc(merchantId, pageable);
    }

    /**
     * 获取已发布的服务列表
     */
    public List<MerchantService> getPublishedServices() {
        return merchantServiceRepository.findByStatusOrderBySortOrderDescCreatedAtDesc(MerchantService.ServiceStatus.PUBLISHED);
    }

    /**
     * 分页获取已发布的服务列表
     */
    public Page<MerchantService> getPublishedServices(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findByStatusOrderBySortOrderDescCreatedAtDesc(MerchantService.ServiceStatus.PUBLISHED, pageable);
    }

    /**
     * 根据分类获取服务
     */
    public List<MerchantService> getServicesByCategory(MerchantService.ServiceCategory category) {
        return merchantServiceRepository.findPublishedServicesByCategory(category);
    }

    /**
     * 分页根据分类获取服务
     */
    public Page<MerchantService> getServicesByCategory(MerchantService.ServiceCategory category, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findPublishedServicesByCategory(category, pageable);
    }

    /**
     * 获取推荐服务
     */
    public List<MerchantService> getRecommendedServices() {
        return merchantServiceRepository.findRecommendedServices();
    }

    /**
     * 分页获取推荐服务
     */
    public Page<MerchantService> getRecommendedServices(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findRecommendedServices(pageable);
    }

    /**
     * 获取热门服务
     */
    public List<MerchantService> getPopularServices() {
        return merchantServiceRepository.findPopularServices();
    }

    /**
     * 分页获取热门服务
     */
    public Page<MerchantService> getPopularServices(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findPopularServices(pageable);
    }

    /**
     * 根据价格范围搜索服务
     */
    public List<MerchantService> getServicesByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) {
        return merchantServiceRepository.findServicesByPriceRange(minPrice, maxPrice);
    }

    /**
     * 分页根据价格范围搜索服务
     */
    public Page<MerchantService> getServicesByPriceRange(BigDecimal minPrice, BigDecimal maxPrice, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findServicesByPriceRange(minPrice, maxPrice, pageable);
    }

    /**
     * 搜索服务
     */
    public List<MerchantService> searchServices(String keyword) {
        return merchantServiceRepository.searchServices(keyword);
    }

    /**
     * 分页搜索服务
     */
    public Page<MerchantService> searchServices(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.searchServices(keyword, pageable);
    }

    /**
     * 根据服务区域搜索服务
     */
    public List<MerchantService> getServicesByArea(String area) {
        return merchantServiceRepository.findServicesByArea(area);
    }

    /**
     * 分页根据服务区域搜索服务
     */
    public Page<MerchantService> getServicesByArea(String area, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return merchantServiceRepository.findServicesByArea(area, pageable);
    }

    /**
     * 根据评分搜索服务
     */
    public List<MerchantService> getServicesByRating(BigDecimal minRating) {
        return merchantServiceRepository.findServicesByRating(minRating);
    }

    /**
     * 增加订单次数
     */
    @Transactional
    public void incrementOrderCount(Long serviceId) {
        merchantServiceRepository.incrementOrderCount(serviceId);
        log.debug("增加服务订单次数: serviceId={}", serviceId);
    }

    /**
     * 增加收藏次数
     */
    @Transactional
    public void incrementFavoriteCount(Long serviceId) {
        merchantServiceRepository.incrementFavoriteCount(serviceId);
        log.debug("增加服务收藏次数: serviceId={}", serviceId);
    }

    /**
     * 减少收藏次数
     */
    @Transactional
    public void decrementFavoriteCount(Long serviceId) {
        merchantServiceRepository.decrementFavoriteCount(serviceId);
        log.debug("减少服务收藏次数: serviceId={}", serviceId);
    }

    /**
     * 更新服务评分
     */
    @Transactional
    public void updateServiceRating(Long serviceId, BigDecimal rating, Integer reviewCount) {
        merchantServiceRepository.updateRatingAndReviewCount(serviceId, rating, reviewCount);
        log.info("更新服务评分: serviceId={}, rating={}, reviewCount={}", serviceId, rating, reviewCount);
    }

    /**
     * 获取服务统计信息
     */
    public java.util.Map<String, Object> getServiceStatistics() {
        List<Object[]> categoryCounts = merchantServiceRepository.countServicesByCategory();
        List<Object[]> statusCounts = merchantServiceRepository.countServicesByStatus();
        
        java.util.Map<String, Object> statistics = new java.util.HashMap<>();
        statistics.put("categoryCounts", categoryCounts);
        statistics.put("statusCounts", statusCounts);
        
        return statistics;
    }

    /**
     * 获取最新发布的服务
     */
    public List<MerchantService> getLatestServices(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return merchantServiceRepository.findLatestPublishedServices(pageable);
    }

    /**
     * 获取最受欢迎的服务
     */
    public List<MerchantService> getMostOrderedServices(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return merchantServiceRepository.findMostOrderedServices(pageable);
    }

    /**
     * 获取评分最高的服务
     */
    public List<MerchantService> getTopRatedServices(int minReviews, int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return merchantServiceRepository.findTopRatedServices(minReviews, pageable);
    }

    /**
     * 通知新服务发布
     */
    private void notifyNewServicePublished(MerchantService service) {
        String message = String.format("新服务发布：%s - %s", service.getTitle(), service.getMerchantName());
        webSocketService.sendAnnouncement(
            "新服务发布",
            message,
            "customers"
        );
    }
}
